<script setup lang="ts">
import { computed, onMounted, reactive, ref, useAttrs, watch } from 'vue';
import { UPDATE_MODEL_EVENT } from '@jctech/constants/event';
import { moment } from '@jctech/utils/date';
import { datepickerEmits, datepickerProps } from './datepickerSrc';

const props = defineProps(datepickerProps);

const emits = defineEmits(datepickerEmits);

defineOptions({
  name: 'CDatepicker'
});

const datepickerRef = ref(null);

const attrs = useAttrs();
const dateValue = computed(() => {
  return moment(props.modelValue).isValid() ? moment(props.modelValue).toDate() : null;
});
const handleUpdate = (value) => {
  if (props.isSourceDate) {
    emits(UPDATE_MODEL_EVENT, value);
  } else {
    let _value = null;
    if (props.type === 'date') {
      _value = moment(value).isValid() ? moment(value).format(props.format) : null;
    }
    if (props.type === 'time') {
      _value = moment(value).isValid() ? moment(value).format(props.format ? props.format : 'HH:mm:ss') : null;
    }
    if (props.type === 'datetime') {
      _value = moment(value).isValid()
        ? moment(value).format(props.format && props.format !== 'YYYY-MM-DD' ? props.format : 'YYYY-MM-DD HH:mm:ss')
        : null;
    }
    console.log(_value);
    emits(UPDATE_MODEL_EVENT, _value);
  }
};
</script>

<template>
  <el-form-item :label="props.label" :prop="props.prop" class="jctech-control-wrapper">
    <el-date-picker
      ref="datepickerRef"
      v-bind="{ ...attrs, ...props }"
      :model-value="dateValue"
      :type="props.type"
      @update:modelValue="handleUpdate"
    />
  </el-form-item>
</template>

<style scoped lang="less"></style>
